package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.wemedia.WemediaConstants;
import com.heima.model.message.PublishArticleConstants;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private AdminFeign adminFeign;
    @Value("${file.oss.web-site}")
    String webSite;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public void autoScanWmNews(Integer wmNewsid) {
        log.info("文章自动审核方法触发    待审核的文章id : {}", wmNewsid);
        // 1. 判断文章id是否为空
        if (wmNewsid == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 根据id查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(wmNewsid);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "id不存在");
        }
        // 3. 判断文章的状态  必须是 1 (待审核)  (避免重复消费)
        if (!wmNews.getStatus().equals(WemediaConstants.WM_NEWS_SUMMIT_STATUS)) {
            return;
        }
        // 4. 抽取文章中 所有的文本内容 和 所有的图片内容
        Map<String, Object> contentAndImages = handleTextAndImages(wmNews);
        // 5. DFA 进行自管理敏感词审核    2 有敏感词不通过     通过继续下一步
        boolean scanSensitive = handleSensitive(wmNews, (String) contentAndImages.get("content"));
        if (!scanSensitive) {
            // 返回false代表审核不成功   结束处理
            log.info("文章审核未通过，原因: 内容中包含敏感词");
            return;
        }
        // 6. 阿里云的文本审核  2 有违规词汇    3 不确定/aliyun未调用成功   通过继续下一步
        boolean scanText = handleTextScan(wmNews, (String) contentAndImages.get("content"));
        if (!scanText) {
            // 返回false代表审核不成功   结束处理
            log.info("文章审核未通过，原因: 内容中包含违规词汇");
            return;
        }
        // 7. 阿里云的图片审核  2 有违规图片    3 不确定/aliyun未调用成功   通过继续下一步
        boolean scanImages = handleImageScan(wmNews, (List<String>) contentAndImages.get("images"));
        if (!scanImages) {
            // 返回false代表审核不成功   结束处理
            log.info("文章审核未通过，原因: 内容中包含违规词汇");
            return;
        }
        // 8. 将文章状态改为 8 自动审核通过
        updateWmNews(wmNews, "审核通过", WmNews.Status.SUCCESS.getCode());
        // 9.   根据文章的发布时间，发送延迟消息 用于定时发布文章( 9 已发布)
        long publishTime = wmNews.getPublishTime().getTime();
        // 当前时间
        long nowTime = new Date().getTime();
        long remainTime = publishTime - nowTime;
        // 发布文章
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                , wmNews.getId()
                , message->{                              // 延时消息 必设置
                    message.getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
                    return message;
                }
        );
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());
    }

    @Autowired
    GreenScan greenScan;

    private boolean handleImageScan(WmNews wmNews, List<String> content) {
        boolean flag = false;
        if (wmNews == null || content == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        try {
            ScanResult scanResult = greenScan.imageUrlScan(content);
            // 阿里云建议:   block 违规    review 进一步人工审核   pass 通过
            switch (scanResult.getSuggestion()) {
                case "block":
                    //失败
                    updateWmNews(wmNews, "文章图片中违规信息: " + scanResult.getLabel(), WmNews.Status.FAIL.getCode());
                    break;
                case "review":
                    //人工
                    updateWmNews(wmNews, "文章图片中有不确定因素，需要进一步人工审核", WmNews.Status.ADMIN_AUTH.getCode());
                    break;
                case "pass":
                    //通过
                    flag = true;
                    break;
                default:
                    //人工
                    updateWmNews(wmNews, "阿里云调用状态异常，需要进一步人工审核:", WmNews.Status.ADMIN_AUTH.getCode());
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            updateWmNews(wmNews, "阿里云调用失败，需要进一步人工审核:", WmNews.Status.ADMIN_AUTH.getCode());
        }
        return flag;
    }


    private boolean handleTextScan(WmNews wmNews, String content) {
        boolean flag = false;
        if (wmNews == null || StringUtils.isBlank(content)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        try {
            ScanResult scanResult = greenScan.greenTextScan(content);
            // 阿里云建议:   block 违规    review 进一步人工审核   pass 通过
            switch (scanResult.getSuggestion()) {
                case "block":
                    //失败
                    updateWmNews(wmNews, "文章内容中包含违规词汇: " + scanResult.getLabel(), WmNews.Status.FAIL.getCode());
                    break;
                case "review":
                    //人工
                    updateWmNews(wmNews, "文章内容中包含不确定因素,交给人工审核", WmNews.Status.ADMIN_AUTH.getCode());
                    break;
                case "pass":
                    //通过
                    flag = true;
                    break;
                default:
                    //人工
                    updateWmNews(wmNews, "阿里云调用状态异常，需要进一步人工审核", WmNews.Status.ADMIN_AUTH.getCode());
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            updateWmNews(wmNews, "阿里云调用失败，需要进一步人工审核:", WmNews.Status.ADMIN_AUTH.getCode());
        }
        return flag;
    }

    private boolean handleSensitive(WmNews wmNews, String content) {
        boolean flag = true;
        // TODO   先查询redis  看redis中是否缓存敏感词数据
        // TODO   如果redis没有  才使用远程查询admin服务
        if (StringUtils.isBlank(content)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章文本内容为空");
        }
        // 远程查询敏感词列表
        ResponseResult<List<String>> sensitives = adminFeign.sensitives();
        if (sensitives == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "查询的敏感词为空");
        }
        List<String> sensitivesData = sensitives.getData();
        //将敏感词 转为DFA数据模型
        SensitiveWordUtil.initMap(sensitivesData);
        //基于DFA扫描 内容中是否包含敏感词
        Map<String, Integer> resultMap = SensitiveWordUtil.matchWords(content);
        //如果有敏感词，将文章状态修改为 2, 并告知原因
        if (!CollectionUtils.isEmpty(resultMap)) {
            updateWmNews(wmNews, "文章中包含敏感词: " + resultMap, WmNews.Status.FAIL.getCode());
            flag = false;
        }
        return flag;
    }

    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        //查询文章所有内容
        String contentJson = wmNews.getContent();
        if (StringUtils.isBlank(contentJson)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        List<Map> maps = JSON.parseArray(contentJson, Map.class);
        //解析文本内容
        String content = maps.stream().filter(map -> "text".equals(map.get("type")))
                .map(m -> (String) m.get("value"))
                .collect(Collectors.joining("_haha_"));
        content = content + "_haha_" + wmNews.getTitle();
        //解析图片内容
        List<String> imageList = maps.stream().filter(map -> "image".equals(map.get("type")))
                .map(m ->m.get("value").toString())
                .collect(Collectors.toList());
        if (StringUtils.isNotBlank(wmNews.getImages())) {
            List<String> urls = Arrays.stream(wmNews.getImages().split(","))
                    .map(url -> webSite+url )
                    .collect(Collectors.toList());
            imageList.addAll(urls);
        }
        // 去重
        imageList = imageList.stream().distinct().collect(Collectors.toList());
        Map<String, Object> result = new HashMap<>();
        result.put("content", content);
        result.put("images", imageList);
        return result;
    }

    private void updateWmNews(WmNews wmNews, String reason, Short status) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }
}
